package com.hk.commons.aware;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * <a href="https://my.oschina.net/longyuan/blog/714355"/>
 *
 * @author Kevin
 */
public class BeanSelfProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof BeanSelfAware beanSelf) {
            beanSelf.setSelf(AopUtils.isAopProxy(bean) ? bean : applicationContext.getBean(beanName));
        }
        return bean;
    }
}
